<?php

namespace api\components;

use common\helpers\commonApi;
use common\helpers\JwtApi;
use common\models\User;
use yii\web\Controller;
use  Yii;

/**
 * Default controller for the `v1` module
 */
class BaseController extends Controller
{
    public $campus_id = '';//校区id
    public static $userid = '';//用户id
    public static $jwtId = 'mamba';//jwtKey


    public function actions()
    {
        $path = Yii::$app->request->pathInfo;
        $jwt = new JwtApi(self::$jwtId);
        $token = $jwt->getRequestToken();
        $id = $jwt->getUserId($token);
        header('Content-Type:application/json; charset=utf-8');
        $notLogin = $this->notLogin();
        if (in_array($path,$notLogin)==false){//必须登录
            if (!$id){
                $da = commonApi::message('请授权登录',false,'',101);
                exit(json_encode($da));
            }
        }
        //设置校区
        $campus_id = Yii::$app->request->headers->get('campusid','');
        $this->campus_id = $campus_id;
        $notCampus = $this->notCampus();
        if (in_array($path,$notCampus)==false){//校区
            if (!$this->campus_id){
                $da = commonApi::message('请选择校区',false);
                exit(json_encode($da));
            }
        }
        if ($id){
            $exists = User::find()->where(['id'=>$id,'status'=>1])->exists();
            if (!$exists){
                $da = commonApi::message('请授权登录',false,'',101);
                exit(json_encode($da));
            }
            self::$userid = $id;
        }
        return true;
    }
    /**
     * 获取model的错误信息
     * @param $model
     * @return string
     */
    protected function getFerror($model){
        $error='';
        if($model && $model->firstErrors){
            foreach($model->firstErrors as $val){
                $error=$val;break;
            }
        }
        return empty($error)?'发生错误了':$error;
    }

    /**
     * 不需要登录
     * @return array
     */
    public function notLogin()
    {
        $arr = [
            'system/index','system/help','system/help-detail','system/bulletin','system/bulletin-detail','home/carousel','goods/classify','goods/goods',
            'goods/good-detail','login/login','home/locate','home/campus','coupon/list','cart/num'
        ];
        return $arr;
    }

    /**
     * 不需要校区
     * @return array
     */
    public function notCampus()
    {
        $arr = [
            'system/index','system/help','system/help-detail','system/bulletin','system/bulletin-detail','home/carousel','goods/classify','goods/goods',
            'goods/good-detail','login/login','home/locate','home/campus','order/list','order/details','order/continue-pay','coupon/list','coupon/receive',
            'cart/num'
        ];
        return $arr;
    }
}
